﻿using Jy.Abp.Application;
using Jy.Abp.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.AuditLogging;
using Volo.Abp.Domain.Repositories;

namespace AbpProjectTemplate.System
{

    /// <summary>
    /// 审计日志
    /// </summary>
    [AppAuthorize(SystemManagementPermissions.Log.AuditLog)]
    public class AuditLogAppService : AppService<AuditLog, Guid>
    {
        public AuditLogAppService(IRepository<AuditLog, Guid> currentRepository)
            : base(currentRepository)
        {
        }

        /// <summary>
        /// 查询审计日志
        /// </summary>
        public async Task<PagedResultDto<AuditLogDto>> GetListAsync(LogFilter filter)
        {
            var query = await Repository.GetQueryableAsync();
            var qr = query
                .WhereIf(filter.BeginDate.HasValue, t => t.ExecutionTime >= filter.BeginDate)
                .WhereIf(filter.EndDate.HasValue, t => t.ExecutionTime < filter.EndDate)
                .WhereIf(filter.Keywords.HasValue(), t => t.Url.Contains(filter.Keywords)
                                                       || t.Exceptions.Contains(filter.Keywords)
                                                       || EF.Functions.Like(nameof(t.ExtraProperties).ToString(), filter.Keywords))
                .ProjectTo<AuditLogDto>(ObjectMapper);

            filter.SetDefaultSortIfNot(nameof(AuditLog.ExecutionTime));
            return await CreatePagedResultAsync(qr, filter);
        }
    }
}
